package com.kuang.design.creation.prototype;

import java.util.HashMap;
import java.util.Map;

public class MyMybatis {


    //缓存user
    private Map<String, User> userCache = new HashMap<>();

    public User getUser(String userName) throws CloneNotSupportedException {

        User user = this.getUserFromDb(userName);

        return user;
    }

    public User getUserWithCache(String userName) throws CloneNotSupportedException {
        User user = null;
        //缓存没有所查对象时才从数据库查询
        if (!userCache.containsKey(userName)) {
            user = this.getUserFromDbWithCache(userName);
        }else {//有从缓存中拿
            //但会产生一个问题，脏缓存问题
            //原型已经拿到，但是不能直接给
             user = userCache.get(userName);//拿到的是本人
            System.out.println("从缓存中拿到的是:"+userName);
            //从user对象中快速得到一个克隆体（克隆人）修改的时候改克隆体不修改原型
            // --用原型模式 在类上实现Cloneable接口 重写clone()方法
            try {
                user  = (User)  user.clone();
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
        }


        return user;
    }

    //模拟从数据库取出数据
    private User getUserFromDb(String userName) throws CloneNotSupportedException {
        System.out.println("从数据查询:" + userName + "并创建对象");
        User user = new User();
        user.setUserName("zhangsan");
        user.setAge(22);
        return user;
    }
    //模拟从数据库取出数据
    private User getUserFromDbWithCache(String userName) throws CloneNotSupportedException {
        System.out.println("从数据查询:" + userName + "并创建对象");
        User user = new User();
        user.setUserName("zhangsan");
        user.setAge(22);
        Object clone = user.clone();
        //给缓存中放一个克隆体
        userCache.put(userName, (User) user.clone());
        return user;
    }

}
